<!-- 房屋管理 -->
<template>
  <div>
    <div class="header">
      <div class="title" style="height: 65px">
        <div style="margin-bottom: 15px; width: 80%; float: left">
          <div style="width: 25%; float: left">
            <a-space direction="vertical" style="width: 100%; margin-left: 13px">
              <a-input-group compact>
                <a-cascader
                  v-model:value="value18"
                  style="width: 100%"
                  :options="options1"
                  expand-trigger="hover" 
                  placeholder="请选择行政区"
                  changeOnSelect @change="onChange"
                />

              </a-input-group>
            </a-space>
		  </div>
			<div style="width: 37%;float: left;margin-top: 15px;margin-left: 10px;"> 
				<a-space style="margin-left: 10px">
            <span>开始时间：</span>
            <a-date-picker v-model:value="startDate" :format="dateFormat" />
          </a-space>
          <a-space style="margin-left: 10px">
            <span>结束时间：</span>
            <a-date-picker v-model:value="endDate" :format="dateFormat" />
          </a-space>
			</div>
			<div style="float: left;width: 8%;margin-top: 20px;margin-left: 15px;">
				<a-space class="search-btn">
					<a-checkbox v-model:checked="checked" @change="getChecked()">66个重点村</a-checkbox>
				</a-space>
			</div>
          <div style="float: left; width: 20%; margin-top: 15px; margin-left: 15px">
            <a-space class="search-btn">
              <a-button type="primary" style="line-height: 25px;" @click="btnSeach">查询</a-button>
            </a-space>
          </div>
        </div>
        <div style="float: left; width: 20%">
          <a-space style="float: right; margin-right: 10px; margin-top: 15px">
            <a-button type="primary" @click="handleExport"> 导出全部明细 </a-button>
          </a-space> 
        </div>
      </div>
      <a-table
        :dataSource="tableData"
        :columns="displayColumns"
        :pagination="false"
        :scroll="{ x: 1500, y: tableHeight }"
        bordered
        :loading="loading"
      >
        <!-- vue3 中的写法 -->
        <template #headerCell="{ column }">
          <template v-if="column.key == 'xzq'">
            <Tooltip placement="top">
              <template #title>
                <span>区县名称</span>
              </template>
              <span>区县名称 </span>
            </Tooltip>
          </template>
          <template v-if="column.key == 'town'">
            <Tooltip placement="top">
              <template #title>
                <span>乡镇名称</span>
              </template>
              <span>乡镇名称 </span>
            </Tooltip>
          </template>
          <template v-if="column.key == 'village'">
            <Tooltip placement="top">
              <template #title>
                <span>村级名称</span>
              </template>
              <span>村级名称 </span>
            </Tooltip>
          </template>
          <template v-if="column.key == 'zcount'">
            <Tooltip placement="top">
              <template #title>
                <span>房屋总数（栋）</span>
              </template>
              <span> 房屋总数（栋） </span>
            </Tooltip>
          </template>
          <template v-if="column.key == 'zccount'">
            <Tooltip placement="top">
              <template #title>
                <span>自查数量（栋）</span>
              </template>
              <span> 自查数量（栋） </span>
            </Tooltip>
          </template>
          <template v-if="column.key == 'zcl'">
            <Tooltip placement="top">
              <template #title>
                <span>自查率</span>
              </template>
              <span> 自查率 </span>
            </Tooltip>
          </template>
          <template v-if="column.key == 'yhcount'">
            <Tooltip placement="top">
              <template #title>
                <span>隐患数量（个）</span>
              </template>
              <span> 隐患数量（个） </span>
            </Tooltip>
          </template>
          <template v-if="column.key == 'zgcount'">
            <Tooltip placement="top">
              <template #title>
                <span>整改数量（个）</span>
              </template>
              <span> 整改数量（个） </span>
            </Tooltip>
          </template>
        </template>
      </a-table>
      <div class="pagination" style="float: right">
        <a-pagination
          show-size-changer
          v-model:current="pageIndex"
          v-model:pageSize="pageSize"
          :total="total"
          @show-size-change="onShowSizeChange"
        />
      </div>

      <Detail
        v-model:visible="visible"
        title="抽屉标题"
        :width="1500"
        :detailTableHeight="detailTableHeight"
        :closable="true"
        :destroyOnClose="true"
        :data="detailData"
        :detailParams="detailParams"
        :currentqx="currentqx"
        :currentTitle="currentTitle"
        @close="handleClose"
      >
        <!-- <p>抽屉内容</p> -->
      </Detail>
      <!-- <BasicTable @register="registerTable">
          <template #id="{ record }"> </template>
      </BasicTable> -->
    </div>
  </div>
</template>

<script lang="ts" setup>
  import moment from 'moment';
  import dayjs from 'dayjs';
  import { ref, reactive, toRefs, onMounted, onBeforeMount, computed, watch } from 'vue';
  import { villageProgreeApi, getRegion } from '/@/api/demo/system'; //统计工作进展
  import { useUserStore } from '/@/store/modules/user';
  import { iTableData, iTableColumns } from './types/table';
  import { iParams } from './types/params';
  import { useGlobSetting } from '/@/hooks/setting';
  import { downloadByUrl } from '/@/utils/file/download';
  import Detail from './component/detailDrawer.vue';
  let userInfo = ref<any>(null);
  const visible = ref(false);
  let detailData = ref<any[]>([]);
  let options1 = ref<any[]>([]);
  let detailParams = ref({}); // 详情参数
  let detailTableHeight = ref<number>(0); // 表格高度
  let tableHeight = ref<number>(0); // 表格高度
  let pageIndex = ref(1);
  let pageSize = ref(15);
  let total = ref(0);
  const userStore = useUserStore();
  const globSetting = useGlobSetting();
  const dateFormat = 'YYYY-MM-DD';
  const startDate = ref<any>(null); // 开始时间
  const endDate = ref<any>(null); // 结束时间
  const checked = ref(false);
  let data = reactive<{
    tableData: iTableData[];
    tableColumns: iTableColumns[];
    wscolsList: { wch: number }[];
    id: number | any;
    loading: Boolean;
    keyWorld: String;
    currentqx: string; // 当前行政区名称
    currentTitle: string;
    cityToken: string | any;
    pageIndex: number;
    pageSize: number;
    total: number;
	startTime:string;
	endTime:string;
  }>({
    // 表格数据
    tableData: [],
    tableColumns: [
      {
        title: '序号',
        dataIndex: 'index',
        key: 'index',
        align: 'center',
        width: 100,
      },
      {
        title: '区县名称',
        dataIndex: 'xzq',
        key: 'xzq',
        align: 'center',
        width: 100,
      },
      {
        title: '乡镇名称',
        dataIndex: 'town',
        key: 'town',
        align: 'center',
        width: 130,
      },
      {
        title: '村级名称',
        dataIndex: 'village',
        key: 'village',
        align: 'center',
        width: 210,
      },
      {
        title: '房屋总数(栋)',
        dataIndex: 'zcount',
        key: 'zcount',
        align: 'center',
        width: 170,
      },
      {
        title: '自查数量（栋）',
        dataIndex: 'zccount',
        key: 'zccount',
        align: 'center',
        width: 170,
        customCell: (row, index, column) => {
          let isNoHzyh = row.xzq !== '汇总' ? true : false;
          let style = 'cursor:pointer;text-decoration: underline; color: blue;';
          let isNoZero = row[column.key] !== 0 ? true : false;
          return {
            style: `${isNoHzyh === true && isNoZero ? style : ''}`,
            class: 'cell-hover',
            onClick: async () => {
              getDetailData(row, index, column, isNoHzyh, isNoZero);
            },
          };
        },
      },
      {
        title: '未自查数量（栋）',
        dataIndex: 'wzccount',
        key: 'wzccount',
        align: 'center',
        width: 170,
        customCell: (row, index, column) => {
          let isNoHzyh = row.xzq !== '汇总' ? true : false;
          let style = 'cursor:pointer;text-decoration: underline; color: blue;';
          let isNoZero = row[column.key] !== 0 ? true : false;
          return {
            style: `${isNoHzyh === true && isNoZero ? style : ''}`,
            class: 'cell-hover',
            onClick: async () => {
				pageIndex.value=1;
				pageSize.value=15;
				getWzcDetailData(row, index, column, isNoHzyh, isNoZero);
            },
          };
        },
      },
      {
        title: '自查率',
        dataIndex: 'zcl',
        key: 'zcl',
        align: 'center',
        width: 130,
      },
      {
        title: '隐患数量（个）',
        dataIndex: 'yhcount',
        key: 'yhcount',
        align: 'center',
        width: 170,
        customCell: (row, index, column) => {
          let isNoHzyh = row.xzq !== '汇总' ? true : false;
          let style = 'cursor:pointer;text-decoration: underline; color: blue;';
          let isNoZero = row[column.key] !== 0 ? true : false;
          return {
            style: `${isNoHzyh === true && isNoZero ? style : ''}`,
            class: 'cell-hover',
            onClick: async () => {
              getYhDetailData(row, index, column, isNoHzyh, isNoZero);
            },
          };
        },
      },
      {
        title: '整改数量（个）',
        dataIndex: 'zgcount',
        key: 'zgcount',
        align: 'center',
        width: 170,
        customCell: (row, index, column) => {
          let isNoHzyh = row.xzq !== '汇总' ? true : false;
          let style = 'cursor:pointer;text-decoration: underline; color: blue;';
          let isNoZero = row[column.key] !== 0 ? true : false;
          return {
            style: `${isNoHzyh === true && isNoZero ? style : ''}`,
            class: 'cell-hover',
            onClick: async () => {
              getZgDetailData(row, index, column, isNoHzyh, isNoZero);
            },
          };
        },
      },
      {
        title: '剩余隐患数量（个）',
        dataIndex: 'syyhcount',
        key: 'syyhcount',
        align: 'center',
        width: 170,
        customCell: (row, index, column) => {
          let isNoHzyh = row.xzq !== '汇总' ? true : false;
          let style = 'cursor:pointer;text-decoration: underline; color: blue;';
          let isNoZero = row[column.key] !== 0 ? true : false;
          return {
            style: `${isNoHzyh === true && isNoZero ? style : ''}`,
            class: 'cell-hover',
            onClick: async () => {
              getSyDetailData(row, index, column, isNoHzyh, isNoZero);
            },
          };
        },
      },
    ],
    id: null,
    loading: true,
    keyWorld: '',
    cityToken: '', // 判断是不是市区 110000 是北京市 展示搜索宽
    currentqx: '', // 当前行政区名称
    currentTitle: '', // 当前详情标题
    total: 0,
    wscolsList: [{ wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 15 }],
  });
  // 表格的 ref Dom名称
  let { tableData, loading, currentqx, currentTitle } = toRefs(data);
  async function getData() {
	if (startDate.value == null) {
      let currentDate = moment().format('YYYY-MM-DD');
      const start: any = dayjs(currentDate);
      const end: any = dayjs(currentDate);
      startDate.value = start;
      endDate.value = end;
      getTime();
    }

    const { role } = userInfo.value;
    let groupname = '';
    if (role === 'City') {
      groupname = 'qxmc';
    } else if (role === 'Area') {
      groupname = 'jzmc';
    } else if (role === 'Street') {
      groupname = 'czmc';
    }
    console.log('*****************value18*****************', value18);
    let params: iParams = {
      groupname: groupname,
      pageIndex: pageIndex.value,
      pageSize: pageSize.value,
	  startTime: moment(startDate.value.$d).format('YYYY-MM-DD'),
      endTime: moment(endDate.value.$d).format('YYYY-MM-DD'),
	  cked:checked.value
    };
    if(value18.value!=undefined)
    {
      params.xzqdm = value18.value[0];
      params.towndm = value18.value[1];
      params.villagedm = value18.value[2];
    }
  
    // console.log('@市级参数', params);
    loading.value = true;
    let res: any = await villageProgreeApi(params);
    console.log('@res--工作进入汇总表', res);

    if (res || res.items.length > 0) {
      loading.value = false;
      data.tableData = [...res.items];
     // data.total = res.total;
      total.value = res.total;
    }
  }
  //重点村是否选中
  function getChecked()
  {
	if(checked.value==false){
		pageIndex.value=1;
	}
  }
   function onChange() {
      getData()
    };

  //已自查数量
  const getDetailData = async (
    row: any,
    index: number,
    column: any,
    isNoHzyh: boolean,
    isNoZero: boolean,
  ) => {
    if (isNoHzyh && isNoZero) {
      let params: iParams = {
        groupbyLever_code: row.xzqdm,
        groupbyLever_code_project: column.key,
        xzqdm: row.xzqdm,
        towndm: row.towndm,
        villagedm: row.villagedm,
        category: '1',
        titlename: '已自查明细',
		startTime: moment(startDate.value.$d).format('YYYY-MM-DD'),
      endTime: moment(endDate.value.$d).format('YYYY-MM-DD'),
      };
      detailParams.value = params;
      data.currentTitle = row.xzq + '-' + row.town + '-' + row.village;
      showDrawer();
    }
  };
  //未自查数量
  const getWzcDetailData = async (
    row: any,
    index: number,
    column: any,
    isNoHzyh: boolean,
    isNoZero: boolean,
  ) => {
    if (isNoHzyh && isNoZero) {
		console.log('未自查房屋明细',)
      let params: iParams = {
        groupbyLever_code: row.xzqdm,
        groupbyLever_code_project: column.key,
        xzqdm: row.xzqdm,
        towndm: row.towndm,
        villagedm: row.villagedm,
        category: '2',
        titlename: '未自查房屋明细',
		startTime: moment(startDate.value.$d).format('YYYY-MM-DD'),
        endTime: moment(endDate.value.$d).format('YYYY-MM-DD'),
      };
      detailParams.value = params;
      data.currentTitle = row.xzq + '-' + row.town + '-' + row.village;
      showDrawer();
    }
  };
  //获取隐患情况
  const getYhDetailData = async (
    row: any,
    index: number,
    column: any,
    isNoHzyh: boolean,
    isNoZero: boolean,
  ) => {
    if (isNoHzyh && isNoZero) {
      let params: iParams = {
        groupbyLever_code: row.xzqdm,
        groupbyLever_code_project: column.key,
        xzqdm: row.xzqdm,
        towndm: row.towndm,
        villagedm: row.villagedm,
        category: '3',
        titlename: '房屋隐患明细',
		startTime: moment(startDate.value.$d).format('YYYY-MM-DD'),
        endTime: moment(endDate.value.$d).format('YYYY-MM-DD'),
      };
      detailParams.value = params;
      data.currentTitle = row.xzq + '-' + row.town + '-' + row.village;
      showDrawer();
    }
  };
  //获取整改情况
  const getZgDetailData = async (
    row: any,
    index: number,
    column: any,
    isNoHzyh: boolean,
    isNoZero: boolean,
  ) => {
    if (isNoHzyh && isNoZero) {
      let params: iParams = {
        groupbyLever_code: row.xzqdm,
        groupbyLever_code_project: column.key,
        xzqdm: row.xzqdm,
        towndm: row.towndm,
        villagedm: row.villagedm,
        category: '4',
        titlename: '房屋整改明细',
		startTime: moment(startDate.value.$d).format('YYYY-MM-DD'),
        endTime: moment(endDate.value.$d).format('YYYY-MM-DD'),
      };
      detailParams.value = params;
      data.currentTitle = row.xzq + '-' + row.town + '-' + row.village;
      showDrawer();
    }
  };
  //获取剩余隐患情况
  const getSyDetailData = async (
    row: any,
    index: number,
    column: any,
    isNoHzyh: boolean,
    isNoZero: boolean,
  ) => {
    if (isNoHzyh && isNoZero) {
      let params: iParams = {
        groupbyLever_code: row.xzqdm,
        groupbyLever_code_project: column.key,
        xzqdm: row.xzqdm,
        towndm: row.towndm,
        villagedm: row.villagedm,
        category: '5',
        titlename: '剩余房屋隐患明细',
		startTime: moment(startDate.value.$d).format('YYYY-MM-DD'),
        endTime: moment(endDate.value.$d).format('YYYY-MM-DD'),
      };
      detailParams.value = params;
      data.currentTitle = row.xzq + '-' + row.town + '-' + row.village;
      showDrawer();
    }
  };
  
  // 切换页码的时候更新  pageIndex 和  pageSize
  const onShowSizeChange = (pageIndex: number, pageSize: number) => {
    // antDesign  自动给  pageIndex 和 pageSize 赋值
    // pageIndex.value = pageIndex;
    // pageSize.value = pageSize;
    // console.log('@pageIndex,pageSize', pageIndex, pageSize);
  };
  function handleExport() {
	
    const uriBase = `${globSetting.apiBaseUrl}${globSetting.apiUrl}`;
    const tk = userStore.getToken;
    getTime();
	let xzqdm="";
	let towndm="";
	let villagedmdm="";
	if(value18.value[0]!=undefined)
	{
		xzqdm=value18.value[0];
	}
	if(value18.value[1]!=undefined)
	{
		towndm=value18.value[1];
	}
	if(value18.value[2]!=undefined)
	{
		villagedmdm=value18.value[2];
	}
    downloadByUrl({
      url:
        uriBase +
        '/houses/evolvestatic/ExportDetailedExcel?access_token=' +
        tk +
        '&startTime=' +
        startDate.value.format('YYYY-MM-DD') +
        '&endTime=' +
        endDate.value.format('YYYY-MM-DD')+
		'&xzqdm=' +
		xzqdm +
        '&towndm=' +
        towndm  +
        '&villagedm=' + villagedmdm,
      target: '_blank',
    });
  }


  function getTime() {
    data.startTime = moment(startDate.value.$d).format('YYYY-MM-DD');
    data.endTime = moment(endDate.value.$d).format('YYYY-MM-DD');
    console.log('@查询参数 -- 开始时间', data.startTime);
    console.log('@查询参数 -- 结束时间', data.endTime);
  }
  function btnSeach()
  {
    getData();
  }
  // 打开抽屉
  function showDrawer() {
    visible.value = true;
  }
  function handleClose() {
    visible.value = false;
  }
  function getUserInfo() {
    const userStore = useUserStore();
    userInfo.value = userStore?.getUserInfo;
  }
  const displayColumns = computed(() => {
    const { role } = userInfo.value;
    let arr: any[] = [];
    if (role === 'City') {
      // qx
      arr = data.tableColumns.filter((item) => item.key !== 'jzmc' && item.key !== 'czmc');
      return arr;
    } else if (role === 'Area') {
      // jz
      arr = data.tableColumns.filter((item) => item.key !== 'czmc' && item.key !== 'qxmc');
      return arr;
    } else if (role === 'Street') {
      // cun
      arr = data.tableColumns.filter((item) => item.key !== 'jzmc' && item.key !== 'qxmc');
      console.log('@Aarr', arr);
      return arr;
    } else {
      return data.tableColumns;
    }
  });
  const getTableHeight = () => {
    setTimeout(() => {
      // detailTableHeight.value = window.innerHeight - 182;
      // tableHeight.value = window.innerHeight - 292;
      detailTableHeight.value = window.innerHeight;
      tableHeight.value = window.innerHeight;
      // console.log(`表格高度`, tableHeight.value);
    });
  };
  // let options: any = await getDistrictCascaderList();
  // console.log('***********行政区划*********', eval('(' + options + ')'));
  async function getRegionData() {
    let res: any = await getRegion();
    options1.value = res;
  }
  // let list: any = await getDistrictCascaderList();
  // var jsonStr = JSON.stringify(list);
  // const options = JSON.parse(jsonStr);
  // console.log('***********行政区划*********', options);
  // console.log('***********行政区划11111111*********', options1);
  const value18 = ref<string[]>([]);
  watch(pageSize, () => {
    console.log('pageSize', pageSize.value);
    getData();
  });
  watch(pageIndex, () => {
    console.log('current', pageIndex.value);
    getData();
  });
  onBeforeMount(() => {
    getUserInfo();
  });
  onMounted(() => {
    console.log('******工作进展统计初始化******');
	getRegionData();
    getData();
    getTableHeight();
  });
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
  #map {
    height: calc(100vh - 140px);
  }

  .x-houseMng-search {
    z-index: 100;
    margin: 6px;
    position: absolute;
  }

  .root-house-mng-main {
    margin: 6px;
  }

  .x-village-tabs {
    //z-index: 100;
    //position: absolute;
    width: 60vw;
    margin-top: 6px;
    margin-left: 40px;
    //background-color: rgba(34, 34, 34, 0.6);
    :deep(.ant-form) {
      margin-top: 6px;
    }

    // :deep(.ant-form-item-label) > label {
    //   color: white;
    // }
  }
  .site-input-group-wrapper .site-input-split {
  background-color: #fff;
}

.site-input-group-wrapper .site-input-right {
  border-left-width: 0;
}

.site-input-group-wrapper .site-input-right:hover,
.site-input-group-wrapper .site-input-right:focus {
  border-left-width: 1px;
}

.site-input-group-wrapper .ant-input-rtl.site-input-right {
  border-right-width: 0;
}

.site-input-group-wrapper .ant-input-rtl.site-input-right:hover,
.site-input-group-wrapper .ant-input-rtl.site-input-right:focus {
  border-right-width: 1px;
}
[data-theme='dark'] .site-input-group-wrapper .site-input-split {
  background-color: transparent;
}
</style>
